package com.bravo.user.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bravo.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import com.bravo.user.entity.User;
import com.bravo.user.service.UserService;

import com.bravo.common.entity.PageResult;
import com.bravo.common.entity.Result;
import com.bravo.common.entity.StatusCode;

import javax.servlet.http.HttpServletRequest;

/**
 * user控制器层
 * @author Yuyong
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private JwtUtil jwtUtil;

	/**
	 * 增加关注数
	 * @param userId
	 * @param x
	 */
	@PostMapping(value = "/incfollow/{userId}/{x}")
	public void incFollowCount(@PathVariable String userId,@PathVariable int x){
		userService.incFollowCount(userId,x);
	}

	/**
	 * 增加粉丝数
	 * @param userId
	 * @param x
	 */
	@PostMapping(value = "/incfans/{userId}/{x}")
	public void incFansCount(@PathVariable String userId,@PathVariable int x){
		userService.incFansCount(userId,x);
	}

	/**
	 * 用户登陆
	 * @param loginMap
	 * @return
	 */
	@PostMapping(value = "/login")
	public Result login(@RequestBody Map<String,String> loginMap){
		User user = userService.findByMobileAndPassword(loginMap.get("mobile"), loginMap.get("password"));
		if (user != null) {
			String token = jwtUtil.createJWT(user.getId(), user.getNickName(), "user");
			Map map = new HashMap();
			map.put("token",token);
			map.put("name",user.getNickName());//昵称
			map.put("avatar",user.getAvatar());//头像
			return new Result(true,StatusCode.OK,"登陆成功",map);
		} else {
			return new Result(false,StatusCode.LOGINERROR,"用户名和密码错误");
		}
	}

	/**
	 * 用户注册
	 * @param user
	 * @param code
	 * @return
	 */
	@PostMapping(value = "/register/{code}")
	public Result register(@RequestBody User user,@PathVariable String code){
		userService.add(user,code);
		return new Result(true,StatusCode.OK,"注册成功");
	}

	/**
	 * 发送短信验证码
	 * @param mobile
	 * @return
	 */
	@PostMapping(value = "sendsms/{mobile}")
	public Result sendSms(@PathVariable String mobile){
		userService.sendSms(mobile);
		return new Result(true,StatusCode.OK,"发送成功");
	}
	/**
	 * 查询全部数据
	 * @return
	 */
	@GetMapping
	public Result findAll(){
		return new Result(true,StatusCode.OK,"查询成功",userService.findAll());
	}
	
	/**
	 * 根据ID查询
	 * @param id ID
	 * @return
	 */
	@GetMapping(value="/{id}")
	public Result findById(@PathVariable String id){
		return new Result(true,StatusCode.OK,"查询成功",userService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@PostMapping(value="/search/{page}/{size}")
	public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
		Page<User> pageList = userService.findSearch(searchMap, page, size);
		return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<User>(pageList.getTotalElements(), pageList.getContent()) );
	}

	/**
     * 根据条件查询
     * @param searchMap
     * @return
     */
    @PostMapping(value="/search")
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(true,StatusCode.OK,"查询成功",userService.findSearch(searchMap));
    }
	
	/**
	 * 增加
	 * @param user
	 */
	@PostMapping
	public Result add(@RequestBody User user){
		userService.add(user);
		return new Result(true,StatusCode.OK,"增加成功");
	}
	
	/**
	 * 修改
	 * @param user
	 */
	@PutMapping(value="/{id}")
	public Result update(@RequestBody User user, @PathVariable String id ){
		user.setId(id);
		userService.update(user);
		return new Result(true,StatusCode.OK,"修改成功");
	}
	
	/**
	 * 删除
	 * @param id
	 */
	@DeleteMapping(value="/{id}")
	public Result delete(@PathVariable String id){
		//获取头信息
		String authHeader = request.getHeader("Authorization");
		if (authHeader == null) {
			return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		}
		if (!authHeader.startsWith("Bearer ")){
			return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		}
		//获取token
		String token = authHeader.substring(7);
		Claims claim = jwtUtil.parseJWT(token);
		if (claim == null) {
			return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		}
		if (!"admin".equals(claim.get("roles"))){
			return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		}
		Claims admin_claim = (Claims) request.getAttribute("admin_claim");
		if (admin_claim == null) {
			return new Result(false,StatusCode.ACCESSERROR,"无权访问");
		}
		userService.deleteById(id);
		return new Result(true,StatusCode.OK,"删除成功");
	}
	
}
